# -*- coding:utf-8 -*-
# Created by Jin(jinzhencheng@outlook.com) at 2018/08/01.

import sys

from bd_spider.config import RedisConfig
from bd_spider.util import db_helper
from bd_spider.entity import Article
from sqlalchemy.sql import exists
from datetime import datetime

from bd_spider.util import logger
reload(sys)
sys.setdefaultencoding('utf-8')

__the_logger = logger.get_logger()
__redis_helper = db_helper.RedisHelper()
__mysql_helper = db_helper.MySQLHelper("bd_article_sys")
__filter_key = RedisConfig.ARTICLE_FILTER


def filter(item):
    is_exists = __redis_helper.is_exists_in_set(__filter_key, item["article_id"])
    if not is_exists:
        __redis_helper.push_to_set(__filter_key, item["article_id"])
        item["is_exists"] = "no"
        __the_logger.info("Push an 'article_id' into article:filter in redis.")

def inject(item):
    entity = Article()
    entity.id = 0
    entity.title = item["title"]
    entity.add_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    entity.baijiahao_id = item["baijiahao_id"]
    entity.article_id = item["article_id"]
    update_dict = dict()
    update_dict[Article.update_time] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    if "publish_time" in item:
        entity.publish_time = item["publish_time"]
        update_dict[Article.publish_time] = item["publish_time"]
    if "src" in item:
        entity.src = item["src"]
        update_dict[Article.src] = item["src"]
    if "view" in item:
        view = item["view"]
        if u"万" in view:
            view = float(view[:len(view) - 1]) * 10000
        entity.view = view
        update_dict[Article.view] = view
    if "comment" in item:
        comment = item["comment"]
        if u"万" in comment:
            comment = float(comment[:len(comment) - 1]) * 10000
        entity.comment = comment
        update_dict[Article.comment] = comment
    session = None
    try:
        __mysql_helper.open_driver()
        session = __mysql_helper.session
        is_in = session.query(exists().where(Article.article_id == item["article_id"])).scalar()
        if is_in:
            row = session.query(Article).filter(Article.article_id == item["article_id"])\
                .update(update_dict)
            __the_logger.info("Update ---- Article:article_id(%s) into bd_article_sys.article table, result: %s "
                              % (item["article_id"], "success" if row else "failure"))
        else:
            session.add(entity)
            __the_logger.info("Add ---- Article:article_id(%s) into bd_article_sys.article table, result: %s"
                              % (item["article_id"], "success"))
        session.commit()
    except Exception, e:
        if session:
            session.rollback()
        __the_logger.error("Inject Article:article_id(%s) into bd_article_sys.article table error, detail: %s" % (item["article_id"], e.message))


